package com.nulldev.util.scripting.cup.vee.registers;

import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;

import com.nulldev.util.scripting.cup.vee.CUPRegister;

public class ShortCUPRegister extends CUPRegister<Short> {

	private final int registerID;

	public ShortCUPRegister(final int registerID) {
		this.registerID = registerID;
	}

	private final AtomicReference<Short> value = new AtomicReference<Short>((short) 0);
	private final AtomicBoolean lock = new AtomicBoolean();

	@Override
	public CUPRegisterType getRegisterType() {
		return CUPRegisterType.SHORT;
	}

	@Override
	public void reset() {
		if (this.lock.get())
			return;
		else
			this.value.set((short) 0);
	}

	@Override
	public Short get() {
		return this.value.get();
	}

	@Override
	public void set(Short value) {
		if (this.lock.get())
			return;
		else
			this.value.set(value);
	}

	@Override
	public boolean valuePresent() {
		return this.value.get() != null;
	}

	@Override
	public int getRegisterID() {
		return this.registerID;
	}

	@Override
	public CUPRegister<Short> setAndReturn(final Short value) {
		if (this.lock.get())
			return this;
		else
			return super.setAndReturn(value);
	}

	public ShortCUPRegister lock() {
		this.lock.set(true);
		return this;
	}

}
